﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace Print_UI
{
    public partial class FrmSemester : CommonForm
    {
        #region Contructors
        public FrmSemester()
        {
            InitializeComponent();
        }
        #endregion
        #region Private members
        private int _id = -1;
        #endregion
        #region Events
        private void FrmSemester_Load(object sender, EventArgs e)
        {

            try
            {
                stcMain.PanelVisibility = DevExpress.XtraEditors.SplitPanelVisibility.Panel1;
                LoadData();
                LoadYear();
                LoadSemester();
                //LoadAuth();
            }
            catch (Exception ex)
            {
                CommonError(ex);

            }
        }
        private void gridView1_DoubleClick(object sender, EventArgs e)
        {
            try
            {
                DevExpress.XtraGrid.Views.Grid.GridView view = (DevExpress.XtraGrid.Views.Grid.GridView)sender;
                Point pt = view.GridControl.PointToClient(Control.MousePosition);
                DevExpress.XtraGrid.Views.Grid.ViewInfo.GridHitInfo info = view.CalcHitInfo(pt);

                if (info.InRow || info.InRowCell)
                {
                    Edit();
                }
            }
            catch (Exception ex)
            {
                CommonError(ex);
            }
        }
        private void btnAdd_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            try
            {
                CheckAuth("Add");
                dxErrorProvider1.ClearErrors();
                stcMain.PanelVisibility = DevExpress.XtraEditors.SplitPanelVisibility.Both;
                _id = -1;
                cboSemester.EditValue = _id;
                cboYear.EditValue = _id;
                chkApproved.Checked = false;
            }
            catch (Exception ex)
            {
                CommonError(ex);
            }
        }
        private void btnEdit_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            try
            {
                Edit();
            }
            catch (Exception ex)
            {
                CommonError(ex);
            }
        }
        private void btnDelete_ItemClick_1(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            try
            {
                object cellValue = gridView1.GetFocusedRowCellValue("ID");
                object status = gridView1.GetFocusedRowCellValue("IsUsed");

                if (cellValue != null)
                {
                    int id = Convert.ToInt32(cellValue);
                    bool _status = Convert.ToBoolean(status);
                    var item = Model.PRI_SemesterSetting.FirstOrDefault(c=>c.ID==id);
                    int year = item.YearID;
                    int semester = item.SemesterID; 
                    bool check = Model.PRI_Template.Where(c => c.YearID == year && c.SemesterID==semester).Count()>0;
                    bool check1 = Model.PRI_StudentInSubject.Where(c => c.YearID == year && c.SemesterID == semester).Count() > 0;
                    bool check2 = Model.PRI_StudentInSemester.Where(c => c.YearID == year && c.SemesterID == semester).Count() > 0;
                    if (check|| check1||check2||_status)
                    {
                        CommonMessage("Học kì đang được sử dụng");
                    }
                    else
                    {
                        if (CommonConfirm("Bạn muốn xóa dữ liệu này?", "XOA"))
                        {
                            stcMain.PanelVisibility = DevExpress.XtraEditors.SplitPanelVisibility.Panel1;
                            _id = -1;
                            var obj = Model.PRI_SemesterSetting.FirstOrDefault(c => c.ID == id);
                            if (obj != null)
                            {
                                Model.DeleteObject(obj);
                                Model.SaveChanges();
                                CommonMessage("Xóa thành công");
                                LoadData();
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                CommonError(ex);
            }
        }
        private void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                if (CheckInput())
                {
                    var obj = Model.PRI_SemesterSetting.FirstOrDefault(c => c.ID == _id);
                    if (obj == null)
                    {
                        obj = new Main_Data.PRI_SemesterSetting();
                        obj.ID = -1;
                        obj.CreatedDate = DateTime.Now;
                        obj.CreatedBy = UserName;
                    }
                    else
                    {
                        obj.ModifiedDate = DateTime.Now;
                        obj.ModifiedBy = UserName;
                    }
                    obj.YearID = Convert.ToInt32(cboYear.EditValue);
                    obj.SemesterID = Convert.ToInt32(cboSemester.EditValue);
                    obj.IsUsed = chkApproved.Checked;
                    if (_id == -1)
                        Model.AddToPRI_SemesterSetting(obj);
                    Model.SaveChanges();

                    CommonMessage("Cập nhật thành công");
                    stcMain.PanelVisibility = DevExpress.XtraEditors.SplitPanelVisibility.Panel1;
                    cboYear.EditValue = _id;
                    cboSemester.EditValue = _id;
                    _id = -1;
                    LoadData();
                }
            }
            catch (Exception ex)
            {
                CommonError(ex);
            }
        }
        private void btnCancle_Click(object sender, EventArgs e)
        {
            try
            {
                stcMain.PanelVisibility = DevExpress.XtraEditors.SplitPanelVisibility.Panel1;
                _id = -1;
                cboSemester.EditValue = _id;
                cboYear.EditValue = _id;
            }
            catch (Exception ex)
            {
                CommonError(ex);
            }
        }
        private void btnRefresh_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            try
            {
              //  RefreshModel();
                LoadData();
            }
            catch (Exception ex)
            {
                CommonError(ex);
            }
        }
        #endregion
        #region Private members
        private void LoadAuth()
        {
            if (Actions != null)
            {
                if (Actions.Contains("Add"))
                    btnAdd.Visibility = DevExpress.XtraBars.BarItemVisibility.Always;
                else
                    btnAdd.Visibility = DevExpress.XtraBars.BarItemVisibility.Never;

                if (Actions.Contains("Edit"))
                {
                    btnEdit.Visibility = DevExpress.XtraBars.BarItemVisibility.Always;
                    AcceptButton = btnSave;
                }
                else
                {
                    btnEdit.Visibility = DevExpress.XtraBars.BarItemVisibility.Never;
                    btnSave.Visible = false;
                    AcceptButton = null;
                }

                if (Actions.Contains("Del"))
                    btnDelete.Visibility = DevExpress.XtraBars.BarItemVisibility.Always;
                else
                    btnDelete.Visibility = DevExpress.XtraBars.BarItemVisibility.Never;
            }
        }
        private void CheckAuth(string key)
        {
            if (Actions != null && Actions.Contains(key))
            {
                if (key == "Add")
                {
                    btnSave.Visible = true;
                    AcceptButton = btnSave;
                    return;
                }
                else
                {
                    btnSave.Visible = false;
                    AcceptButton = null;
                }

                if (key == "Edit")
                {
                    btnSave.Visible = true;
                    AcceptButton = btnSave;
                    return;
                }
                else
                {
                    btnSave.Visible = false;
                    AcceptButton = null;
                }
            }
        }
        private void LoadData()
        {
            var query = from c in Model.PRI_SemesterSetting
                        join d in Model.CAT_Year on c.YearID equals d.ID
                        join e in Model.CAT_Semester on c.SemesterID equals e.ID
                        select new
                        {
                            c.ID,
                            d.Name,
                            e.SemesterName,
                            c.IsUsed
                        };
            gridControl1.DataSource = query;

        }
        private void LoadYear()
        {
            Dictionary<int, string> dic = new Dictionary<int, string>();
            dic.Add(-1, "--- Chọn Năm Học ---");
            foreach (var item in Model.CAT_Year.OrderBy(c => c.Name))
            {
                dic.Add(item.ID, item.Name);
            }
            
            cboYear.Properties.ValueMember = "Key";
            cboYear.Properties.DisplayMember = "Value";
            cboYear.Properties.DataSource = dic;
            cboYear.EditValue = -1;
        }
        private void LoadSemester()
        {
            Dictionary<int, string> dic = new Dictionary<int, string>();
            dic.Add(-1, "--- Chọn Học Kì ---");
            foreach (var item in Model.CAT_Semester.OrderBy(c => c.SemesterName))
            {
                dic.Add(item.ID, item.SemesterName);
            }
            cboSemester.Properties.ValueMember = "Key";
            cboSemester.Properties.DisplayMember = "Value";
            cboSemester.Properties.DataSource = dic;
            cboSemester.EditValue = -1;
        }
        private bool CheckInput()
        {
            bool result = true;
            int year = Convert.ToInt32(cboYear.EditValue);
            int semester = Convert.ToInt32(cboSemester.EditValue);
            dxErrorProvider1.ClearErrors();
            if ((Convert.ToInt32(cboSemester.EditValue) == -1) && (Convert.ToInt32(cboYear.EditValue) == -1))
            {
                dxErrorProvider1.SetError(cboYear, "Chưa chọn năm học");
                dxErrorProvider1.SetError(cboSemester, "Chưa chọn học kì");
                return false;
            }
            else
            {
                if (Convert.ToInt32(cboSemester.EditValue) == -1)
                {
                    dxErrorProvider1.SetError(cboSemester, "Chưa chọn học kì");
                    return false;
                }
                if (Convert.ToInt32(cboYear.EditValue) == -1)
                {
                    dxErrorProvider1.SetError(cboYear, "Chưa chọn năm học");
                    return false;
                }
            }
            if (Model.PRI_SemesterSetting.FirstOrDefault(c => c.ID != _id && c.YearID == year && c.SemesterID == semester) != null)
            {
                dxErrorProvider1.SetError(cboSemester, "Đã tồn tại năm học học kì này");
                result = false;
            }
            return result;
        }
        private void Edit()
        {
            object cellValue = gridView1.GetFocusedRowCellValue("ID");
            if (cellValue != null)
            {
                CheckAuth("Edit");
                dxErrorProvider1.ClearErrors();
                stcMain.PanelVisibility = DevExpress.XtraEditors.SplitPanelVisibility.Both;
                _id = Convert.ToInt32(cellValue);
                var obj = Model.PRI_SemesterSetting.FirstOrDefault(c => c.ID == _id);
                if (obj != null)
                {
                    cboYear.EditValue = obj.YearID;
                    cboSemester.EditValue = obj.SemesterID;
                    chkApproved.Checked = obj.IsUsed;
                }
            }
        }
        
        #endregion

  



       
    }

    
}
    

